import { IDetailProp } from '@/types/modal'
import { Modal } from 'antd'
import { useImperativeHandle, useState } from 'react'
import api from '@/api/orderApi'
import { Order } from '@/types/api'
import { message } from '@/utils/AntdGlobal'

export default function OrderMarker(props: IDetailProp) {
  const [visble, setVisible] = useState(false) // 显示隐藏
  const [orderId, setOrderId] = useState('')
  const [markers, setMarkers] = useState<{ lng: string; lat: string; id: number }[]>([])
  useImperativeHandle(props.mRef, () => {
    return {
      open
    }
  })

  // 弹框
  const open = async (orderId: string) => {
    setOrderId(orderId)
    setVisible(true)
    const detail = await api.getOrderDetail(orderId) // 详情信息
    renderMap(detail) // 渲染地图
  }

  // 渲染地图
  const renderMap = (detail: Order.OrderItem) => {
    const map = new window.BMapGL.Map('markerMap') // 初始化地图
    map.centerAndZoom(
      detail.cityName, // 设置中心点坐标（也可以传入城市）
      12 // 地图缩放倍数
    )
    map.enableScrollWheelZoom() // 开启鼠标滚轮缩放
    const scaleCtrl = new window.BMapGL.ScaleControl()
    const zoomCtrl = new window.BMapGL.ZoomControl()
    map.addControl(scaleCtrl) // 添加比例尺(距离单位)
    map.addControl(zoomCtrl) // 添加缩放控件
    // 创建标注(数据库的)
    detail.route?.map(item => {
      createMarker(map, item.lng, item.lat)
    })
    // 绑定事件（现创建的）
    map.addEventListener('click', function (e) {
      createMarker(map, e.latlng.lng, e.latlng.lat) // 点击的经纬度
    })
  }
  // 创建标注对象并添加到地图
  const createMarker = (map: any, lng: string, lat: string) => {
    const id = Math.random() // 随机ID
    markers.push({ lng, lat, id })
    const point = new window.BMapGL.Point(lng, lat) // 经纬度
    const marker = new window.BMapGL.Marker(point) // 创建实例
    marker.id = id // id
    const markerMenu = new window.BMapGL.ContextMenu() // 绑定右键实例
    // 添加属性
    markerMenu.addItem(
      new window.BMapGL.MenuItem('删除', function () {
        map.removeOverlay(marker)
        const index = markers.findIndex(item => item.id === marker.id)
        markers.splice(index, 1)
        setMarkers([...markers])
      })
    )
    setMarkers([...markers])
    marker.addContextMenu(markerMenu) // 添加右键
    map.addOverlay(marker) // 添加打点
  }
  // 更新打点
  const handleOk = async () => {
    await api.updateOrderInfo({
      orderId,
      route: markers
    })
    message.success('打点成功')
    handleCancel()
  }
  // 关闭弹框
  const handleCancel = () => {
    setVisible(false)
    setMarkers([])
  }
  return (
    <Modal
      title='地图打点'
      width={1100}
      open={visble}
      okText='确定'
      cancelText='取消'
      onOk={handleOk}
      onCancel={handleCancel}
    >
      <div id='markerMap' style={{ height: 500 }}></div>
    </Modal>
  )
}
